#include "StdAfx.h"
#include "DPostprocessManager.h"
#include "../../DGlobals.h"
#include <SFML/Graphics.hpp>
#include "DFade.h"
#include "DWaveblast.h"

using namespace Postprocesses;

DPostprocessManager::DPostprocessManager(void)
{
}

DPostprocessManager::~DPostprocessManager(void)
{
}

DPostprocessManager& DPostprocessManager::instance()
{
    static DPostprocessManager inst;
    return inst;
}

bool DPostprocessManager::isSupported()
{
    return m_bEffectsSupported;
}

void DPostprocessManager::init()
{
    m_bEffectsSupported = sf::PostFX::CanUsePostFX();

    if(!m_bEffectsSupported)
    {
        return;
    }
     
    addEffect("Fade");
	addEffect("Waveblast");

	// Fade
    m_ppFade.reset(new DFade);
    m_ppFade->m_effect = m_effects["Fade"];

	// Waveblast
	m_ppWaveblast.reset(new DWaveblast);
    m_ppWaveblast->m_effect = m_effects["Waveblast"];
}

bool DPostprocessManager::addEffect(const std::string& name)
{
    std::string fullPath = DGlobals::instance().sfxPath() + name + ".sfx";
    boost::shared_ptr<sf::PostFX> effect;
    effect.reset(new sf::PostFX);

    if(!effect->LoadFromFile(fullPath))
    {
        assert(false);
        return false;
    }

    m_effects[name] = effect;

    return true;
}

void DPostprocessManager::update(float dt)
{
	if(m_ppWaveblast->isActive())
	{
		m_ppWaveblast->update(dt);
	}

    if(m_ppFade->isActive())
    {
        m_ppFade->update(dt);
    }
}

void DPostprocessManager::render(boost::shared_ptr<DIRenderer> renderer)
{
	if(m_ppWaveblast->isActive())
	{
		m_ppWaveblast->render(renderer);
	}

    if(m_ppFade->isActive())
    {
        m_ppFade->render(renderer);
    }
}

void DPostprocessManager::activateFadeIn(float fSpeed)
{
    if(!m_ppFade->isActive())
    {
        boost::shared_ptr<DFade> fade(boost::static_pointer_cast<DFade>(m_ppFade));
        fade->startFade(true, fSpeed);
    }
}

void DPostprocessManager::activateFadeOut(float fSpeed)
{
    if(!m_ppFade->isActive())
    {
        boost::shared_ptr<DFade> fade(boost::static_pointer_cast<DFade>(m_ppFade));
        fade->startFade(false, fSpeed);
    }
}

void DPostprocessManager::activateBlast(float duration, const vec2& originScreen)
{
	if(!m_ppWaveblast->isActive())
	{
		boost::shared_ptr<DWaveblast> blast(boost::static_pointer_cast<DWaveblast>(m_ppWaveblast));
		blast->startBlast(duration, originScreen);
	}
}